package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.StrategyTheme;
import cn.wolfcode.luowowo.query.StrategyThemeQuery;
import cn.wolfcode.luowowo.repository.StrategyThemeRepository;
import cn.wolfcode.luowowo.service.IStrategyThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class StrategyThemeServiceImpl implements IStrategyThemeService {


    @Autowired
    private StrategyThemeRepository strategyThemeRepository;


    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);
        strategyThemeRepository.save(strategyTheme);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {

        strategyThemeRepository.save(strategyTheme);
    }

    @Override
    public void delete(String id) {
        strategyThemeRepository.deleteById(id);

    }

    @Override
    public StrategyTheme get(String id) {
        Optional<StrategyTheme> op = strategyThemeRepository.findById(id);
        if (op.isPresent()){
            StrategyTheme strategyTheme = op.get();
            return strategyTheme;
        }
        return null;
    }

    @Override
    public List<StrategyTheme> list()
    {
        return strategyThemeRepository.findAll();
    }

    // 分页操作
    @Override
    public Page<StrategyTheme> query(StrategyThemeQuery qo) {

        Query query = new Query();
        // 查询总页数
        long count = mongoTemplate.count(query, StrategyTheme.class);
        if (count == 0){
            return Page.empty();
        }

        // 分页排序
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        query.with(pageable);

        List<StrategyTheme> list = mongoTemplate.find(query, StrategyTheme.class);


        return new PageImpl<>(list,pageable,count);

    }
    

}
